package util

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"log"
	"mindonmap/pkgs/setting"
)

// DeleteFileObject_R2_single 删除 r2 单个文件
func DeleteFileObject_R2_single(filePathUrl string) bool {

	var aws3 = setting.GetAWSS3()
	AccessKeyID := aws3.AccessKeyID
	SecretAccessKey := aws3.SecretAccessKey
	S3Bucket := aws3.S3Bucket
	AccountId := aws3.AccountId
	//S3Host := aws3.S3Host

	creds := credentials.NewStaticCredentialsProvider(AccessKeyID, SecretAccessKey, "")

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(creds),
		config.WithRegion("auto"), // Cloudflare R2 doesn't use regions, but this is required by the SDK
	)
	if err != nil {
		fmt.Println(err)
	}
	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.BaseEndpoint = aws.String(fmt.Sprintf("https://%s.r2.cloudflarestorage.com", AccountId))
	})

	_, err = client.DeleteObject(context.Background(), &s3.DeleteObjectInput{
		Bucket: aws.String(S3Bucket),
		Key:    aws.String(filePathUrl), // 使用 filePathUrl 作为 Key
	})

	if err != nil {
		fmt.Println(err)
		return false
	}

	return true
}

// DeleteObject_r2_multipleFile 删除 r2 多个文件
func DeleteObject_r2_multipleFile(filePathUrls []string) bool {

	var aws3 = setting.GetAWSS3()
	AccessKeyID := aws3.AccessKeyID
	SecretAccessKey := aws3.SecretAccessKey
	S3Bucket := aws3.S3Bucket
	AccountId := aws3.AccountId

	creds := credentials.NewStaticCredentialsProvider(AccessKeyID, SecretAccessKey, "")

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(creds),
		config.WithRegion("auto"), // Cloudflare R2 doesn't use regions, but this is required by the SDK
	)
	if err != nil {
		log.Fatalf("unable to load SDK config, %v", err)
	}
	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.BaseEndpoint = aws.String(fmt.Sprintf("https://%s.r2.cloudflarestorage.com", AccountId))
	})

	objects := make([]types.ObjectIdentifier, len(filePathUrls))
	for i, url := range filePathUrls {
		objects[i] = types.ObjectIdentifier{Key: aws.String(url)}
	}

	_, err = client.DeleteObjects(context.Background(), &s3.DeleteObjectsInput{
		Bucket: aws.String(S3Bucket),
		Delete: &types.Delete{
			Objects: objects,
		},
	})

	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}
